package com.zhugang.week13.stack;

import java.util.Stack;

/**
 * @program algorithms
 * @description: IsValid
 * @author: chanzhugang
 * @create: 2022/11/03 16:25
 */
public class IsValid2 {

    /**
     * 20 有效的括号
     * https://leetcode.cn/problems/valid-parentheses/
     *
     * @param s
     * @return
     */
    public boolean isValid2(String s) {
        // 最简洁的代码：逆向思维，栈中存的是相反的括号。
        // 栈适合做连连消的题目
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(')');
            } else if (c == '[') {
                stack.push(']');
            } else if (c == '{') {
                stack.push('}');
            } else if (stack.isEmpty() || stack.pop() != c) {
                return false;
            }
        }
        return stack.isEmpty();
    }


}